<?php
//公共函数文件

const _PASS_     = 'wadyemomo0..';
const _Chat_Num_ = 10; //聊天频繁次数设置

const _HEADER_PASS_ = '12wadye123lhchat0..'; //header秘钥值

const _ENCODE_ = 'Z8JpD6HzGUfe3KRhas1blWy9FI7rkjcvOu2Qdwn5YmTAMqtBNC4SPgEXoiLx0V'; //id加解密密钥

const _PUB_ID_ = 'NNh'; //大厅id：to_uid为0时的加密id

const _CAPTCHA_ = 4; //验证码位数

//私钥
const _PRIVATE_ = "-----BEGIN RSA PRIVATE KEY-----
MIICXwIBAAKBgQDAhQ7xiwPIAc1dt5Jlnzb7sRjZoUhxSUPcOrLKRE4tZoxL9tK2
owvEKv+xKcIws8VW794A0I6MEH9P3nVGAlHj/88h/ayj5n/Q6H/jbb401zTZhaoT
XhggaGq8TcSx3Ozq5ypzKS7S7p+n0kIUKyCMtKQJDjA2JK6srRaFXfs9EQIDAQAB
AoGBAKd8WpbKoNyErNxmUsdz7wqidIMI7BQacB4NNvP+3qBiwZVowsI/MIJWAiJn
uNhT3U+X2GSPDCRQSeH7H71rUT9tWICAnaqIRW8yul3cfVrDMTlyv9IppyDRuJPy
vx1WJDlBSK6XVkNMDeAvXnhmm5x5opcvU3E+/ejnYv7awKyRAkEA7h/lLMqnYDFT
6RRQMp4fcsCCCDsot30Um9R1DXuavbzuY2rHGMZVlJoE4GmQX6qcEQJkJ2LEIo0y
aMMaXuPJ7QJBAM74w0PvWR+GbFR32AFx+fSswHemHPbRq30EYn2jIPw9KIz9UQhm
CQWoYtpJvKNuj/6Lq7DeqFlysIX2OLISSzUCQQDNy1TlvBKhKKBrPHn+9Pca1lLK
yE3tHjV0Y03yJBPczO59jyeYOrh1oBJ8297BPxJ4BMgH3ezCK6MYNR2SSm0VAkEA
qaitmBCpg/gS8SLUREsD1JePpgTbFVBGPNLNUaPZNCuGBBzawgGyP5sKfVmYcnf9
PXGMqg26/qfPH+D4FLB+SQJBAIpCrNzUZIq0QEu75HWeLhy/bVwO/D0XQhQ8YqdL
3uqp28gde5sAKGmAiGMYAcqyG+cKUrZ1IFSwXMpSUKR9+X8=
-----END RSA PRIVATE KEY-----";

//Redis配置链接
function initRedis()
{
    $redis = new Redis();
    $redis->connect('127.0.0.1', '6379');
    $redis->auth('123ywh321lhwad');
    return $redis;
}

//随机生成字符串
function random($length) {
     srand(date("s"));
     $possible_charactors = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ";
     $string = "";
     while(strlen($string)<$length) {
          $string .= substr($possible_charactors,(rand()%(strlen($possible_charactors))),1);
     }
     return($string);
}

//ip黑名单
function ip_black($ip)
{
    $black = [
            '122.233.177.26',
            '106.110.131.48',
            '114.238.28.12',
            '59.42.201.199',
            '59.42.200.252',
        ];
   
   if (in_array($ip,$black))
   {
       return false;
   } else {
       return true;
   }
}

//统一接口返回
function displayJson($code,$msg,$data = array())
{
    $ret['code']   = $code;
    $ret['msg']    = $msg;
    $ret['data']   = $data;

    echo json_encode($ret,JSON_UNESCAPED_UNICODE);die;
}

/*
* 获取用户真实IP
*/
function plum_get_realIP()
{
    //strcasecmp 比较两个字符，不区分大小写。返回0，>0，<0。
    if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } else if (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } else if (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $ip = getenv('REMOTE_ADDR');
    } else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    $res =  preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
    return $res;
}

/**
 * 获取 IP  地理位置
 * @Return: array
 */
function plum_ip_get_address($ip = '')
{
    $url = 'http://api.map.baidu.com/location/ip?ip='.$ip.'&ak=2iiY6MzGuG55hRXs9GufzodP7qDKdABB&coor=bd09ll';
    if ($data=file_get_contents($url))
    {
        $data = json_decode($data,true);

        if (!empty($data) && $data['status'] == 0) {
            $result['province'] = $data['content']['address_detail']['province'];
            $result['city']     = $data['content']['address_detail']['city'];

        }else{
            $result['province'] = '未知';
            $result['city']     = '未知';
        }

        return $result;
    }
}


/**
 * 接收头信息
 **/
function em_getallheaders()
{
    foreach ($_SERVER as $name => $value)
    {
        if (substr($name, 0, 5) == 'HTTP_')
        {
            $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
        }
    }
    return $headers;
}

/*
 * 上传图片
 * @param $img //图片文件
 * @param $basedir //存储路径
 * @param string[] $imagesExt
 */
function uploadImageCommon($img,$basedir,$imagesExt=['jpg','png','jpeg','gif','mp4'])
{
    $ret['ec'] = 400;
    $ret['em'] = '文件上传失败';

    //获取上图片后缀
    $type = substr($img['name'], strrpos($img['name'], ".")+1);
    $type = strtolower($type); //转小写
    $rand = rand(1000, 9999);
    //命名图片名称
    $pics = date("YmdHis") . $rand .'.'. $type;

    if (!in_array($type,$imagesExt))
    {
        $ret['em'] = '文件格式暂不支持';
        return $ret;
    }

    $chSize = 5120000; //默认5M限制
    
    $chs    = '5M';
    
    if ($type == 'mp4')
    {
        $chSize = $chSize * 4; //视频20M
        $chs    = '20M';
    }
    
    //限制
    if ($img['size'] > $chSize)
    {
        $ret['em'] = '文件大小超过限制('.$chs.')';
        return $ret;
    }

    //上传路径
    if (!is_dir($basedir))
    {
        //创建目录
        $mkdir = @mkdir($basedir, 0777,true);

        if (!$mkdir)
        {
            $ret['em'] = '创建目录失败';
            return $ret;
        }
    }

    $pic_path = $basedir."/{$pics}";

    //移动到指定目录，上传图片
    $res = move_uploaded_file($img['tmp_name'], $pic_path);

    if ($res)
    {
        $ret['ec']  = 200;
        $ret['em']  = '文件上传成功';
        $ret['url'] = $pic_path;
        $ret['type'] = $type;
        return $ret;
    } else {
        return $ret;
    }
}

/*过滤除img外html标签*/
function cleanhtml($str,$tags='<img>'){//过滤时默认保留html中的<a><img>标签
    $search = array(
        '@<script[^>]*?>.*?</script>@si',  // Strip out javascript
        /*                      '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags*/
        '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
        '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments including CDATA
    );
    $str = preg_replace($search, '', $str);
    $str = strip_tags($str,$tags);
    return $str;
}

/*
 * 发送邮件相关配置
 */
function sendEmail($that)
{
    $that->load->library("PHPMailer");
    $mail = new PHPMailer\PHPMailer\PHPMailer(true);

    $mail->IsSMTP(); // 启用SMTP
    $mail->Host       = 'smtp.sina.com'; //SMTP服务器 以QQ邮箱为例子
    $mail->Port       = 465;  //邮件发送端口
    $mail->SMTPAuth   = true;  //启用SMTP认证
    $mail->SMTPSecure = "ssl";   // 设置安全验证方式为ssl

    $mail->CharSet    = "UTF-8"; //字符集
    $mail->Encoding   = "base64"; //编码方式

    $mail->Username   = 'wadye0220@sina.com';  //你的邮箱
    $mail->Password   = 'ccb234b01b8ade2d';    //密码/授权码
    $mail->Subject    = '在线聊天有新的头像投稿'; //邮件标题

    $mail->From       = 'wadye0220@sina.com';  //发件人地址（也就是你的邮箱）
    $mail->FromName   = '叶念安';  //发件人姓名

    $mail->AddAddress('1298025852@qq.com', "叶念安"); //添加收件人（地址，昵称）
    $mail->Body = '在线聊天有新的头像投稿'; //邮件主体内容

    //发送
    if ($mail->Send()) {
        return true;
    } else {
        return false;
    }
}

// 违规词检测 start

function no_mom_str($content)
{
    $words = array(
            'by756khaq6jaoktpr032bzvgffnt',
            'byp2zae6fc66ioz4ucym',
            'img01.pp3q.com',
            '点我发车',
            'by1376',
            'by77731',
            'view_window',
            'YA_c1626322780_92361',
            '开撸',
        );
        
    $banned = generateRegularExpression($words);

    //检查违禁词
    $res_banned = check_words($banned,$content);

    return $res_banned;
}

/**
 * @describe 数组生成正则表达式
 * @param array $words
 * @return string
 */
function generateRegularExpression($words)
{
    $regular = implode('|', array_map('preg_quote', $words));
    return "/$regular/i";
}

/**
 * @describe 字符串 生成正则表达式
 * @param array $words
 * @return string
 */
function generateRegularExpressionString($string){
      $str_arr[0]=$string;
      $str_new_arr=  array_map('preg_quote', $str_arr);
      return $str_new_arr[0];
}
/**
 * 检查敏感词
 * @param $banned
 * @param $string
 * @return bool|string
 */
function check_words($banned,$string)
{    $match_banned=array();
    //循环查出所有敏感词

    $new_banned=strtolower($banned);
    $i=0;
    do{
        $matches=null;
        if (!empty($new_banned) && preg_match($new_banned, $string, $matches)) {
            $isempyt=empty($matches[0]);
            if(!$isempyt){
                $match_banned = array_merge($match_banned, $matches);
                $matches_str=strtolower(generateRegularExpressionString($matches[0]));
                $new_banned=str_replace("|".$matches_str."|","|",$new_banned);
                $new_banned=str_replace("/".$matches_str."|","/",$new_banned);
                $new_banned=str_replace("|".$matches_str."/","/",$new_banned);
            }
        }
        $i++;
        if($i>20){
            $isempyt=true;
            break;
        }
    }while(count($matches)>0 && !$isempyt);

    //查出敏感词
    if($match_banned){
        return $match_banned;
    }
    //没有查出敏感词
    return array();
}
// 违规词检测 end

// id加密--只适用整型
function encode_uid($int)
{
    //判断是否为整型
    if (!is_int($int)) {
        return false;
    }
    //将传入数字转换成十六进制分割成数组
    $hexArr = str_split(dechex($int));
    //将密钥分割成数组
    $keyArr = str_split(_ENCODE_);
    //密钥长度，推荐62
    $keyLen = count($keyArr);
    //随机数字
    $rand = mt_rand(0, $keyLen - 1);
    //将随机值压入结果开头
    $str = $keyArr[$rand];
    //验证码
    $verfy = $keyArr[($keyLen - $rand + strlen($int)) % $keyLen];
    //循环十六进制每一位数字，替换成密钥里的值
    foreach ($hexArr as $v) {
        $offset = hexdec($v) + $rand;
        $str .= $keyArr[$offset % $keyLen];
    }
    //将验证码压入结果末尾并返回
    return $str . $verfy;
}

// id解密
function decode_uid($str)
{
    //验证$str是否合法
    if (! preg_match('/^[0-9a-zA-Z]{2,10}$/', $str)) {
        return false;
    }
    //将传入字符串分割成数组
    $strArr = str_split($str);
    //密钥
    $key = _ENCODE_;
    //将密钥分割成数组
    $keyArr = str_split(_ENCODE_);
    //密钥长度
    $keyLen = count($keyArr);
    //十六进制数值
    $hex = '';
    //获取随机数
    $rand = strpos($key, array_shift($strArr));
    //获取验证码
    $verfy = array_pop($strArr);
    //循环每一个字串并转换成十六进制
    foreach ($strArr as $k => $v) {
        if (strpos($key, $v) >= $rand) {
            $hex .= dechex(strpos($key, $v) - $rand);
        } else {
            $hex .= dechex($keyLen - $rand + strpos($key, $v));
        }
    }
    //十六进制转换成十进制
    $dec = hexdec($hex);
    //判断验证码是否正确
    if ($verfy !== $keyArr[($keyLen - $rand + strlen($dec)) % $keyLen]) {
        return false; 
    }
    return $dec;
}
